/**
 * 
 */
package importExport;

import importExport.log.WuselLogger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import dataTypes.Constants;
import dataTypes.Environment;
import dataTypes.environment.IntersectionPoint;

/**
 * @author Kevin Wagner
 * @version 1.0
 *
 */
public class EnvironmentImportExport {
	
	/**
	 * @param props
	 * @return list of environments
	 */
	public static ArrayList<Environment> importEnvironment(Properties props){
		ArrayList<Environment> temp=new ArrayList<Environment>();
		File dir = new File(props.getProperty("environmentDir", "Environment"));
		if(!dir.exists()||!dir.isDirectory()){
			WuselLogger.log.warn("No Environment Directory found!");
			return temp;
		}
		File[] envFiles = dir.listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				return pathname.isFile()
						&& pathname.getName().endsWith(".environment");
			}
		});
		for (int i = 0; i < envFiles.length; i++) {
			temp.add(importEnvironment(envFiles[i]));
			if (temp.get(i) == null) {
				temp.remove(null);
			}
		}
		return temp;
	}
	
	private static Environment importEnvironment(File filename) {
		Environment env=new Environment();
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(filename);
			NodeList nList = doc.getElementsByTagName("Name");
			env.setName(nList.item(0).getTextContent());
			nList = doc.getElementsByTagName("Population");
			env.setPopulation(Integer.parseInt(nList.item(0).getTextContent()));
			//System.out.println("Name: "+env.getName());
			nList = doc.getElementsByTagName("IntersectionPoints");
			nList=((Element)nList.item(0)).getElementsByTagName("Point");
			for(int i=0;i<nList.getLength();i++){
				Element e=(Element) nList.item(i);
				long id=Long.parseLong(e.getElementsByTagName("ID").item(0).getTextContent());
				int x=Integer.parseInt(e.getElementsByTagName("X").item(0).getTextContent());
				int y=Integer.parseInt(e.getElementsByTagName("Y").item(0).getTextContent());
				//System.out.println("Intersection Point: "+x+";"+y);
				env.addIntersectionPoint(id, x, y);
			}
		} catch (Exception e) {
			WuselLogger.log.error(e.getLocalizedMessage());
			return null;
		}
		return env;
	}
	
	/**
	 * @param env
	 * @param props 
	 * @return status of deleting
	 */
	public static boolean deleteEnvironmentFile(Environment env, Properties props) {
		File dir = new File(props.getProperty("environmentDir", "Environment"));
		File f=new File(dir.getPath()+Constants.FILESEPARATOR+env.getName()+".environment");
		if(!f.exists()){
			return true;
		}
		return f.delete();
	}
	

	/**
	 * @param env
	 * @param props
	 * @return status of export
	 */
	public static boolean exportEnvironment(ArrayList<Environment> env, Properties props) {
		File f = new File(props.getProperty("environmentDir", "Environment"));
		if (!f.exists()||f.isDirectory()) {
			f.mkdir();
		}
		for (int i = 0; i < env.size(); i++) {
			if (!exportEnvironment(env.get(i), f)) {
				WuselLogger.log.error("Error in Exporting Environment");
				return false;
			}

		}
		return true;
	}
	
	/**
	 * @param env
	 * @param dir
	 * @return status of saving
	 */
	public static boolean exportEnvironment(Environment env, File dir) {
		File temp = new File(dir.getAbsolutePath()
				+ Constants.FILESEPARATOR + env.getName()
				+ ".environment");
		try {
			FileWriter fw = new FileWriter(temp, false);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>");
			bw.newLine();
			bw.append("<Environment>");
			bw.newLine();
			bw.append("\t<Name>" + env.getName() + "</Name>");
			bw.newLine();
			bw.append("\t<Population>" + env.getPopulation() + "</Population>");
			bw.newLine();
			bw.append("\t<IntersectionPoints>");
			bw.newLine();
			for(int i=0;i<env.getIntersectionPoints().size();i++){
				IntersectionPoint p=env.getIntersectionPoints().get(i);
				bw.append("\t\t<Point>");
				bw.newLine();
				bw.append("\t\t\t<ID>" + p.getId() + "</ID>");
				bw.newLine();
				bw.append("\t\t\t<X>" + p.getX() + "</X>");
				bw.newLine();
				bw.append("\t\t\t<Y>" + p.getY() + "</Y>");
				bw.newLine();
				bw.append("\t\t</Point>");
				bw.newLine();
			}
			bw.append("\t</IntersectionPoints>");
			bw.newLine();
			bw.append("</Environment>");
			bw.flush();
			bw.close();
		} catch (Exception e) {
			WuselLogger.log.error(e.getLocalizedMessage());
			return false;
		}
		return true;
	}

}
